import pymysql
import hashlib
import random
import string
from datetime import datetime
import db_config  # 引入配置文件

def generate_salt(length=8):
    """生成随机盐值"""
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

def get_encrypt_password(password, salt):
    """
    按照 FastAdmin 的加密规则加密密码
    加密逻辑为：md5(md5(password) + salt)
    """
    # 使用 hashlib 计算两次 MD5 加密
    hashed_password = hashlib.md5(password.encode('utf-8')).hexdigest()
    encrypted_password = hashlib.md5((hashed_password + salt).encode('utf-8')).hexdigest()
    return encrypted_password

def sync_ecs_to_fa():
    try:
        # 使用配置文件中的数据库连接配置
        ecs_conn = pymysql.connect(**db_config.ecs_db_config)
        fa_conn = pymysql.connect(**db_config.fa_db_config)

        ecs_cursor = ecs_conn.cursor(pymysql.cursors.DictCursor)
        fa_cursor = fa_conn.cursor()

        # 查询 ECS 用户数据
        ecs_cursor.execute("SELECT * FROM ecs_users")
        ecs_users = ecs_cursor.fetchall()

        # 遍历 ECS 用户并插入到 FA 表
        for user in ecs_users:
            # 构造 FastAdmin 用户数据
            mobile = user['mobile_phone']
            last_ip = user['last_ip']

            # 生成 nickname：手机号中间四位隐藏（如：177****2793）
            if mobile and len(mobile) == 11:
                nickname = f"{mobile[:3]}****{mobile[-4:]}"
            else:
                nickname = "匿名用户"  # 如果手机号为空或格式不对，则设置默认值

            # 生成 salt 和加密密码
            salt = generate_salt()
            plain_password = f"maigeyin{mobile}" if mobile else "maigeyin"
            password = get_encrypt_password(plain_password, salt)

            fa_user = {
                'id': user['user_id'],
                'group_id': 0,
                'username': user['user_name'],
                'nickname': nickname,
                'password': password,  # 加密后的密码
                'salt': salt,          # 随机生成的 salt
                'email': user['email'],
                'mobile': mobile,
                'avatar': '',  # 默认值
                'level': 0,  # 默认等级为0
                'gender': user['sex'],
                'birthday': user['birthday'] if user['birthday'] != '0000-00-00' else None,
                'bio': '',  # 默认格言为空
                'money': user['user_money'],
                'score': user['pay_points'],
                'successions': 1,  # 默认值
                'maxsuccessions': 1,  # 默认值
                'prevtime': user['last_login'],
                'logintime': user['last_login'],
                'loginip': last_ip,
                'loginfailure': 0,  # 默认值
                'loginfailuretime': None,  # 默认值
                'joinip': last_ip,  # 设置为 ECS 的 last_ip
                'jointime': user['reg_time'],
                'createtime': int(datetime.now().timestamp()),
                'updatetime': int(datetime.now().timestamp()),
                'token': '',  # 默认值
                'status': 'normal',  # 固定为 normal
                'verification': '',  # 默认值
                'froms': 'pc',  # 固定值
                'adminuser_id': 0,  # 默认值
                'bzcontent': '',  # 默认值
            }

            # 插入数据到 fa_user 表
            insert_query = """
            INSERT INTO fa_user (
                id, group_id, username, nickname, password, salt, email, mobile, avatar,
                level, gender, birthday, bio, money, score, successions, maxsuccessions,
                prevtime, logintime, loginip, loginfailure, loginfailuretime, joinip, jointime,
                createtime, updatetime, token, status, verification, froms, adminuser_id, bzcontent
            ) VALUES (
                %(id)s, %(group_id)s, %(username)s, %(nickname)s, %(password)s, %(salt)s, %(email)s, %(mobile)s, %(avatar)s,
                %(level)s, %(gender)s, %(birthday)s, %(bio)s, %(money)s, %(score)s, %(successions)s, %(maxsuccessions)s,
                %(prevtime)s, %(logintime)s, %(loginip)s, %(loginfailure)s, %(loginfailuretime)s, %(joinip)s, %(jointime)s,
                %(createtime)s, %(updatetime)s, %(token)s, %(status)s, %(verification)s, %(froms)s, %(adminuser_id)s, %(bzcontent)s
            )
            """

            try:
                fa_cursor.execute(insert_query, fa_user)
                print(f"Successfully synced user_id: {user['user_id']}")
            except Exception as e:
                print(f"Failed to sync user_id: {user['user_id']}, error: {e}")

        # 提交事务
        fa_conn.commit()

    except Exception as e:
        print(f"Error: {e}")

    finally:
        # 关闭数据库连接
        if 'ecs_cursor' in locals():
            ecs_cursor.close()
        if 'fa_cursor' in locals():
            fa_cursor.close()
        if 'ecs_conn' in locals():
            ecs_conn.close()
        if 'fa_conn' in locals():
            fa_conn.close()

if __name__ == "__main__":
    sync_ecs_to_fa()
